package huriezy.quickcontacts.activities.fragments;

import huriezy.quickcontacts.R;
import huriezy.quickcontacts.activities.UserSelectionFragmentActivity;
import huriezy.quickcontacts.activities.interfaces.ITerminableListener;
import huriezy.quickcontacts.models.LogDebug;

import java.net.URISyntaxException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.internal.ImageDownloader;
import com.facebook.internal.ImageRequest;
import com.facebook.internal.ImageResponse;

public class UserScreenFragment extends Fragment {

	public static final String	USER_SCREEN_TYPE	= "userScreenType";
	public static final String	SELECTED_USER		= "selectedUser";

	private String				userScreenType		= null;
	private Bundle				selectedUser		= null;
	private ITerminableListener	onTerminateListener	= null;

	private final Handler		imageHandler		= new Handler(Looper.getMainLooper());
	private Bitmap				lastProfilePicture	= null;

	public static UserScreenFragment newInstance(String screenType, Bundle selectedUser) {
		UserScreenFragment fragment = new UserScreenFragment();
		Bundle args = new Bundle();
		args.putString(USER_SCREEN_TYPE, screenType);
		args.putBundle(SELECTED_USER, selectedUser);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_user_screen, null);

		Bundle args = getArguments();
		if (args == null) {
			args = savedInstanceState;
		}
		if (args != null) {
			userScreenType = args.getString(USER_SCREEN_TYPE);
			selectedUser = args.getBundle(SELECTED_USER);
		}

		initSelectedUser(view);
		initActions(view);

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		initAddButtonText(getView());
	}

	private void initSelectedUser(View view) {
		String uid = null;
		String name = null;
		String email = null;
		String address = null;

		if (selectedUser != null) {
			uid = selectedUser.getString(FacebookPickerFragment.UID_FIELD);
			name = selectedUser.getString(FacebookPickerFragment.NAME_FIELD);
			email = selectedUser.getString(FacebookPickerFragment.EMAIL_FIELD);
			address = selectedUser.getString(FacebookPickerFragment.ADDRESS_FIELD);
		}
		else {
			LogDebug.warn("Selected user is null", getClass());
		}

		// Get picture from UID
		ImageView userPicture = (ImageView) view.findViewById(R.id.social_picture_imageView);

		initUserPicture(userPicture, uid, selectedUser);

		TextView nameView = (TextView) view.findViewById(R.id.social_name_textView);
		TextView emailView = (TextView) view.findViewById(R.id.social_email_textView);
		TextView addressView = (TextView) view.findViewById(R.id.social_address_textView);

		if (nameView != null) {
			if (name != null && name.length() > 0 && !name.equals("null")) {
				nameView.setVisibility(View.VISIBLE);
				nameView.setText(name);
			}
			else {
				selectedUser.remove(FacebookPickerFragment.NAME_FIELD);
				nameView.setVisibility(View.GONE);
			}
		}

		if (emailView != null) {
			if (email != null && email.length() > 0 && !email.equals("null")) {
				emailView.setVisibility(View.VISIBLE);
				emailView.setText(email);
			}
			else {
				selectedUser.remove(FacebookPickerFragment.EMAIL_FIELD);
				emailView.setVisibility(View.GONE);
			}
		}
		if (addressView != null) {
			if (address != null && address.length() > 0 && !address.equals("null")) {
				addressView.setVisibility(View.VISIBLE);
				addressView.setText(address);
			}
			else {
				selectedUser.remove(FacebookPickerFragment.ADDRESS_FIELD);
				addressView.setVisibility(View.GONE);
			}
		}

	}

	private void initUserPicture(final ImageView userPicture, final String uid, final Bundle user) {
		final Class<?> debugInfo = getClass();
		Thread imgUrlThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ImageRequest.Builder requestBuilder = new ImageRequest.Builder(getActivity(),
							ImageRequest.getProfilePictureUrl(uid, 256, 256));

					ImageRequest request = requestBuilder.setAllowCachedRedirects(true).setCallerTag(this)
							.setCallback(new ImageRequest.Callback() {
								@Override
								public void onCompleted(ImageResponse response) {
									lastProfilePicture = response.getBitmap();
									final Bitmap usedBitmap = lastProfilePicture;
									if (lastProfilePicture != null && userPicture != null) {
										imageHandler.post(new Runnable() {
											@Override
											public void run() {
												userPicture.setImageBitmap(usedBitmap);
												user.putParcelable(FacebookPickerFragment.PICTURE_BITMAP_FIELD,
														usedBitmap);
											}
										});
									}
									else {
										selectedUser.remove(FacebookPickerFragment.PICTURE_BITMAP_FIELD);
										LogDebug.info("Removed bitmap picture", debugInfo);
									}
								}
							}).build();
					ImageDownloader.downloadAsync(request);
				}
				catch (URISyntaxException e) {
					LogDebug.error("Syntax error in native URI", getClass(), e);
				}

			}
		});
		imgUrlThread.start();

	}

	/**
	 * 
	 * @param view
	 */
	private void initAddButtonText(View view) {
		TextView askFriendButton = (TextView) view.findViewById(R.id.social_ask_friend_button);
		Resources resources = getActivity().getResources();
		String buttonText = null;
		if (askFriendButton != null && resources != null) {
			if (userScreenType != null) {
				if (userScreenType.equals(UserSelectionFragmentActivity.FACEBOOK_SOCIAL_TYPE)) {
					buttonText = resources.getString(R.string.add_facebook_contact);
				}
				else if (userScreenType.equals(UserSelectionFragmentActivity.GOOGLEPLUS_SOCIAL_TYPE)) {
					buttonText = resources.getString(R.string.add_googleplus_contact);
				}
				else {
					buttonText = "Incompatible type";
				}
			}
			else {
				buttonText = "Null type";
			}
			askFriendButton.setText(buttonText);
		}
	}

	/**
	 * Init actions
	 * 
	 * @param view
	 */
	private void initActions(View view) {
		// TextView askFriendButton = (TextView)
		// view.findViewById(R.id.social_ask_friend_button);
		TextView parseInfoButton = (TextView) view.findViewById(R.id.social_parse_info_button);

		// if (askFriendButton != null) {
		// askFriendButton.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// askUserToAdd();
		// }
		// });
		// }
		if (parseInfoButton != null) {
			parseInfoButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					replaceInformations();
				}
			});
		}
	}

	private void replaceInformations() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(R.string.replace_information_title_text);
		builder.setMessage(R.string.replace_information_message_text);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialogInterface, int i) {
				if (onTerminateListener != null) {
					onTerminateListener.onFinishActivity(selectedUser);
				}
			}
		});
		builder.setNegativeButton("Cancel", null);
		builder.show();
	}

	public void setSelectedUser(Bundle selectedUser) {
		this.selectedUser = selectedUser;
	}

	public void setScreenType(String type) {
		userScreenType = type;
	}

	public void setOnTerminateListener(ITerminableListener terminableListener) {
		this.onTerminateListener = terminableListener;
	}
}
